package com.mz.ozy.activity.shop;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.baidu.location.d.g;
import com.google.gson.Gson;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;
import com.mz.ozy.R;
import com.mz.ozy.activity.home.SimpleShareListener;
import com.mz.ozy.activity.me.MsgActivity;
import com.mz.ozy.adapter.ShopDetailAdapter;
import com.mz.ozy.adapter.ShopDetailBannerAdapter;
import com.mz.ozy.adapter.ShopEvaluateAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.bean.FirmOrderBean;
import com.mz.ozy.bean.GoodsImgBean;
import com.mz.ozy.bean.MeBean;
import com.mz.ozy.bean.ShopDetailBean;
import com.mz.ozy.bean.ShopSpecListBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.model.MeModel;
import com.mz.ozy.mvp.presenter.ShopDetailPresenter;
import com.mz.ozy.mvp.view.ShopDetailContract;
import com.mz.ozy.net.MyObserver;
import com.mz.ozy.utils.AppUtils;
import com.mz.ozy.utils.CalendarUtils;
import com.mz.ozy.utils.RxUtil;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.widget.dialog.GoodsSpecDialog;
import com.mz.ozy.widget.dialog.ShareDialog;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.sobot.chat.ZCSobotApi;
import com.sobot.chat.api.model.Information;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jzvd.Jzvd;
import me.jessyan.autosize.internal.CancelAdapt;
import okhttp3.ResponseBody;

public class ShopDetailActivity extends BaseActivity<ShopDetailContract.View, ShopDetailPresenter> implements ShopDetailContract.View, ViewPager.OnPageChangeListener, CancelAdapt {
    @BindView(R.id.rollPagerView)
    RollPagerView mRollPagerView;
    @BindView(R.id.tv_goods_price)
    TextView mTvPrice;
    @BindView(R.id.shopDetail)
    TextView mTvShopDetail;
    @BindView(R.id.tv_shop_desc)
    TextView mTvShopDesc;
    @BindView(R.id.tv_goods_unit)
    TextView mTvGoodsUnitBv;
    @BindView(R.id.tv_unit_price)
    TextView mTvUnitPrice;
    @BindView(R.id.tv_choose_rules)
    TextView mTvChooseRules;
    @BindView(R.id.tv_select_rules)
    TextView mTvSelectRules;
    @BindView(R.id.rv_shop_detail)
    RecyclerView mRvShopDetail;
    @BindView(R.id.carNumberTv)
    TextView mCarNumberTv;//购物车数量
    @BindView(R.id.tv_rollpager_hint)
    TextView mTvRollpagerHint;
    @BindView(R.id.rv_food_evaluate)
    RecyclerView mRvFoodEvaluate;
    @BindView(R.id.iv_shop_info_star)
    ImageView mIvShopInfoStar;
    @BindView(R.id.iv_shop_share)
    ImageView mIvShopShare;
//    @BindView(R.id.dragview)
//    ImageView mDragview;
    @BindView(R.id.customerserviceview)
    ImageView mCustomerServiceView;

    @BindView(R.id.tv_detail_parameter)
    TextView mTvDetailParameter;
    @BindView(R.id.ll_detail_parameter)
    LinearLayout mLlDetailParameter;

    @BindView(R.id.tv_user_evaluation)
    TextView mTvUserEvaluate;
    @BindView(R.id.tv_view_reviews)
    TextView mTvReviews;
    @BindView(R.id.tv_shop_about)
    TextView mTvShopAbout;
    @BindView(R.id.tv_start_time)
    TextView mTvStartTime;
    @BindView(R.id.rl_shop_car)
    RelativeLayout rlShopCar;
    @BindView(R.id.rl_joinCar)
    RelativeLayout rlJoinCar;
    @BindView(R.id.topView)
    RelativeLayout topView;

    private ShopEvaluateAdapter mEvaluateAdapter;
    private ShopDetailBannerAdapter mBannerAdapter;
    private ShopDetailAdapter mDetailAdapter;
    private GoodsSpecDialog mSpecPopupWindow;
    private ShopDetailBean.ShopMapBean bean;
    private List<GoodsImgBean> mGoodsImgListBeans = new ArrayList<>();
    private int buyNumber = 1;//购买数量
    private String goodsId;
    private int mOpType = 0;
    private ShopSpecListBean mSpecListBeans;
    private int mGgId = -1;
    private int showSpec = 0;
    private boolean isFirstLoad = true;
    private boolean isFirstResume = true;
    private boolean comEmpty;
    private int mPosition = 0;
    private int isCon = 0;
    private long curTime;
    private int tag;//10000  欧花专区标识

    //private int flag = 0;
    private float mOriginalX, mOriginalY;//手指按下时的初始位置
    private float lastX, lastY; //最后一次触摸事件的坐标
    private int containerWidth, containerHeight;    //容器宽高
    private MeModel mModel;
    private MeBean mMeBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_detail);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initTitle();
        QMUIStatusBarHelper.translucent(this);
        setTitleBarMargin();
        getMeInfo(this);
        initLottery();
//        EventBus.getDefault().register(this);
        mRollPagerView.setAnimationDurtion(500);
        mRollPagerView.setPlayDelay(-1);
//        mRollPagerView.setHintView(new ColorPointHintView(this, Color.WHITE, this.getResources().getColor(R.color.text_color_80ffffff)));
//        mRollPagerView.setHintView(new IconHintView(this, R.drawable.arrow_down, R.drawable.arrow_up));
        mRollPagerView.setHintView(null);
        mBannerAdapter = new ShopDetailBannerAdapter(this, mGoodsImgListBeans);
        mRollPagerView.setAdapter(mBannerAdapter);
        mCarNumberTv.setVisibility(View.GONE);
        goodsId = getIntent().getStringExtra("goodsId");
        tag = getIntent().getIntExtra("tag", 0);
        /*if (tag == Constants.OB_TYPE) {
            rlShopCar.setVisibility(View.GONE);
            rlJoinCar.setVisibility(View.GONE);

        }*/
        showSpec = getIntent().getIntExtra("show", 0);
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        Date curDate = cal.getTime();
        curTime = curDate.getTime();


        mDetailAdapter = new ShopDetailAdapter(null);
        mRvShopDetail.setLayoutManager(new LinearLayoutManager(this));
        mRvShopDetail.setAdapter(mDetailAdapter);
        mRvShopDetail.setNestedScrollingEnabled(false);
        mRollPagerView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
//                Intent intent = new Intent(ShopDetailActivity.this, PhotoViewActivity.class);
//                intent.putExtra("url", mGoodsImgListBeans.get(position).getImg_zt());
//                startActivity(intent);
            }
        });
        mRollPagerView.getViewPager().addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                final int index = position + 1;
                String hint = index + "/" + mBannerAdapter.getCount();
                mTvRollpagerHint.setText(hint);
                if (position != 0) {
                    mBannerAdapter.setPause(true);
                }
//                else {
//                    mBannerAdapter.setPause(false);
//                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        mIvShopInfoStar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.onGoodsFollow(ShopDetailActivity.this, goodsId);
            }
        });
        mIvShopShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showShareDialog();
            }
        });

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);//把布局设为横行排列
        mRvFoodEvaluate.setLayoutManager(layoutManager1);
        mEvaluateAdapter = new ShopEvaluateAdapter(null);
        mRvFoodEvaluate.setAdapter(mEvaluateAdapter);

        mPresenter.obtainShopDetailInfo(this, goodsId);
    }
    //获取用户信息，用于进入客服
    private void getMeInfo(Activity activity) {
        mModel = new MeModel();
        mModel.getMeInfo(activity)
                .compose(RxUtil.rxSchedulerHelper(this.<ResponseBody>bindToLifecycle()))
                .subscribe(new MyObserver<MeBean>(this) {
                    @Override
                    public void onSuccesss(MeBean bean) {
                        mMeBean = bean;
                    }
                });
    }

    private void initLottery() {
//        topView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
//            @Override
//            public boolean onPreDraw() {
//                //不能直接在onCreate()方法中得到宽高,会得到0,所以注册视图树的观察者来得到宽高
//                //OnPreDrawListener是当一个视图树将要绘制时，所要调用的回调函数的接口类
//                containerWidth = topView.getWidth();
//                containerHeight = topView.getHeight();
//                return true;
//            }
//        });
//
//        mDragview.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                switch (motionEvent.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        //记录触摸时的坐标,这里为什么要用getRawX()和getRawY()相信理解getX(),getY()和getRawX(),getRawY()的区别就知道为什么了
//                        lastX = motionEvent.getRawX();
//                        lastY = motionEvent.getRawY();
//                        mOriginalX = motionEvent.getRawX();
//                        mOriginalY = motionEvent.getRawY();
//                        //return true对事件进行拦截,不继续下发,防止继续响应onClick事件.
//                        return true;
//                    case MotionEvent.ACTION_MOVE:
//                        //每次移动的距离
//                        float distanceX = motionEvent.getRawX() - lastX;
//                        float distanceY = motionEvent.getRawY() - lastY;
//
//                        //控件将要移动到的位置,先计算一下,不在ofFloat()方法中再计算是因为要防止控件移动到容器之外.
//                        float nextX = mDragview.getX() + distanceX;
//                        float nextY = mDragview.getY() + distanceY;
//                        //如果将要移动到的 x 轴坐标小于0,则等于0,防止移出容器左边
//                        if (nextX < 0)
//                            nextX = 0;
//                        //防止移出容器右边
//                        if (nextX > containerWidth - mDragview.getWidth())
//                            nextX = containerWidth - mDragview.getWidth();
//                        //防止移出容器顶边
//                        if (nextY < 0)
//                            nextY = 0;
//                        //防止移出容器底边
//                        if (nextY > containerHeight - mDragview.getHeight())
//                            nextY = containerHeight - mDragview.getHeight();
//                        //利用属性动画改变控件的x,y坐标
//                        ObjectAnimator mObjectAnimatorX = ObjectAnimator.ofFloat(mDragview, "x", mDragview.getX(), nextX);
//                        ObjectAnimator mObjectAnimatorY = ObjectAnimator.ofFloat(mDragview, "y", mDragview.getY(), nextY);
//                        AnimatorSet mAnimatorSet = new AnimatorSet();
//                        mAnimatorSet.playTogether(mObjectAnimatorX, mObjectAnimatorY);
//                        mAnimatorSet.setDuration(0);
//                        mAnimatorSet.start();
//                        //移动完之后记录当前坐标
//                        lastX = motionEvent.getRawX();
//                        lastY = motionEvent.getRawY();
//                        break;
//                    case MotionEvent.ACTION_UP:
//                        if (Math.abs(motionEvent.getRawX() - mOriginalX) <
//                                Utils.dp2px(ShopDetailActivity.this, 3) &&
//                                Math.abs(motionEvent.getRawY() - mOriginalY) <
//                                        Utils.dp2px(ShopDetailActivity.this, 3)) {
//                            CarActivity.go(ShopDetailActivity.this);
//                        }
//                        break;
//                }
//                return false;
//            }
//        });

        mCustomerServiceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Information info = new Information();
                info.setApp_key("f970b1112b8447b6abe76c7acbf450cd");
                info.setPartnerid(Constants.uid);
                info.setUser_nick(mMeBean.getNickname());
                info.setUser_name(mMeBean.getUsername());
                info.setUser_tels(mMeBean.getUsername());
                info.setFace(mMeBean.getUseravatar());
                ZCSobotApi.openZCChat(ShopDetailActivity.this, info);
            }
        });

//        mCustomerServiceView.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                switch (motionEvent.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        //记录触摸时的坐标,这里为什么要用getRawX()和getRawY()相信理解getX(),getY()和getRawX(),getRawY()的区别就知道为什么了
//                        lastX = motionEvent.getRawX();
//                        lastY = motionEvent.getRawY();
//                        mOriginalX = motionEvent.getRawX();
//                        mOriginalY = motionEvent.getRawY();
//                        //return true对事件进行拦截,不继续下发,防止继续响应onClick事件.
//                        return true;
//                    case MotionEvent.ACTION_MOVE:
//                        //每次移动的距离
//                        float distanceX = motionEvent.getRawX() - lastX;
//                        float distanceY = motionEvent.getRawY() - lastY;
//
//                        //控件将要移动到的位置,先计算一下,不在ofFloat()方法中再计算是因为要防止控件移动到容器之外.
//                        float nextX = mCustomerServiceView.getX() + distanceX;
//                        float nextY = mCustomerServiceView.getY() + distanceY;
//                        //如果将要移动到的 x 轴坐标小于0,则等于0,防止移出容器左边
//                        if (nextX < 0)
//                            nextX = 0;
//                        //防止移出容器右边
//                        if (nextX > containerWidth - mCustomerServiceView.getWidth())
//                            nextX = containerWidth - mCustomerServiceView.getWidth();
//                        //防止移出容器顶边
//                        if (nextY < 0)
//                            nextY = 0;
//                        //防止移出容器底边
//                        if (nextY > containerHeight - mCustomerServiceView.getHeight())
//                            nextY = containerHeight - mCustomerServiceView.getHeight();
//                        //利用属性动画改变控件的x,y坐标
//                        ObjectAnimator mObjectAnimatorX = ObjectAnimator.ofFloat(mCustomerServiceView, "x", mCustomerServiceView.getX(), nextX);
//                        ObjectAnimator mObjectAnimatorY = ObjectAnimator.ofFloat(mCustomerServiceView, "y", mCustomerServiceView.getY(), nextY);
//                        AnimatorSet mAnimatorSet = new AnimatorSet();
//                        mAnimatorSet.playTogether(mObjectAnimatorX, mObjectAnimatorY);
//                        mAnimatorSet.setDuration(0);
//                        mAnimatorSet.start();
//                        //移动完之后记录当前坐标
//                        lastX = motionEvent.getRawX();
//                        lastY = motionEvent.getRawY();
//                        break;
////                    case MotionEvent.ACTION_UP:
////                        if (Math.abs(motionEvent.getRawX() - mOriginalX) <
////                                Utils.dp2px(ShopDetailActivity.this, 3) &&
////                                Math.abs(motionEvent.getRawY() - mOriginalY) <
////                                        Utils.dp2px(ShopDetailActivity.this, 3)) {
////                            MsgActivity.go(ShopDetailActivity.this);
////                        }
////                        break;
//                }
//                return false;
//            }
//        });
    }

    private ShareDialog mDialog;

    /**
     * 显示分享弹窗
     */
    private void showShareDialog() {
        if (mDialog == null) {
            mDialog = new ShareDialog(this);
            mDialog.setOnDialogListener(new ShareDialog.onDialogListener() {
                @Override
                public void onConfirm(SHARE_MEDIA platform) {
                    shareSingleImage(platform);
                    mDialog.toggleDialog();
                }
            });
        }
        mDialog.toggleDialog();
    }

    public void shareSingleImage(SHARE_MEDIA platform) {
        ShareAction shareAction = new ShareAction(this);
        shareAction.withMedia(getShareBitmap()).setPlatform(platform).setCallback(new SimpleShareListener() {

            @Override
            public void onResult(SHARE_MEDIA shareMedia) {
//                if (shareMedia == SHARE_MEDIA.SINA) {
//                ToastUtils.showToast("分享成功");
//                }
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                super.onError(share_media, throwable);
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                super.onCancel(share_media);
            }

            @Override
            public void onStart(SHARE_MEDIA shareMedia) {
                super.onStart(shareMedia);
                if ((shareMedia == SHARE_MEDIA.WEIXIN || shareMedia == SHARE_MEDIA.WEIXIN_CIRCLE) && !UMShareAPI.get(ShopDetailActivity.this)
                        .isInstall(ShopDetailActivity.this, SHARE_MEDIA.WEIXIN)) {
                    ToastUtils.showToast("您未安装微信客户端");
                }
                if (shareMedia == SHARE_MEDIA.QQ && !UMShareAPI.get(ShopDetailActivity.this).isInstall(ShopDetailActivity.this, SHARE_MEDIA.QQ)) {
                    ToastUtils.showToast("您未安装QQ客户端");
                }
                if (shareMedia == SHARE_MEDIA.SINA && !UMShareAPI.get(ShopDetailActivity.this).isInstall(ShopDetailActivity.this, SHARE_MEDIA.SINA)) {
                    ToastUtils.showToast("您未安装微博客户端");
                }
            }

        }).share();
    }

    private UMWeb getShareBitmap() {
        String yourName = "";
//        if (!TextUtils.isEmpty(dataItem.getUname())) {
//            yourName = dataItem.getUname();
//        } else if (!TextUtils.isEmpty(dataItem.getUsername())) {
//            yourName = dataItem.getUsername();
//        }
        String userlink = Constants.KEY.SHARL + "Miaosfk"/*mBusBean.getInvitecode()*/;
        UMWeb web = new UMWeb(userlink);//连接地址
        web.setTitle(yourName);//标题
        web.setDescription(yourName + "给您分享了他的名片，快来看看吧！");//描述
//        if (TextUtils.isEmpty(dataItem.getUseravatar())) {
//            web.setThumb(new UMImage(this, R.mipmap.logo)); //本地缩略图
//        } else {
//            web.setThumb(new UMImage(this, dataItem.getUseravatar())); //网络缩略图
//        }
        return web;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mBannerAdapter != null) {
            mBannerAdapter.setPause(true);
        }
        Jzvd.resetAllVideos();
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (!isFirstResume) {
//            if (mBannerAdapter != null) {
//                mBannerAdapter.setPause(false);
//            }
//        }
//        isFirstResume = false;
    }

    /**
     * 设置沉浸式状态栏时，要把标题栏往下移动状态栏的高度
     */
    protected void setTitleBarMargin() {
        int length = AppUtils.getStatusBarHeight(this);
        //注意布局是哪种Layout
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(titleBar.getLayoutParams());
        lp.setMargins(0, length, 0, 0);
        titleBar.setLayoutParams(lp);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void obtainShopDetailInfoSuccess(ShopDetailBean detailBean) {
        if (detailBean.getBuyCarNum() > 0) {
            mCarNumberTv.setVisibility(View.VISIBLE);
            mCarNumberTv.setText(detailBean.getBuyCarNum() + "");
        } else {
            mCarNumberTv.setVisibility(View.GONE);
        }
        isCon = detailBean.getIsCon();
        if (detailBean.getIsCon() == 0) {
            mIvShopInfoStar.setImageResource(R.mipmap.icon_detail_collect);
        } else {
            mIvShopInfoStar.setImageResource(R.mipmap.icon_detail_select);
        }
        final ShopDetailBean.BMapBean bMapBean = detailBean.getbMap();
        if (bMapBean != null) {
            mTvShopAbout.setText(bMapBean.getAbout());
        } else {
            mTvShopAbout.setText("");
        }
        mTvUserEvaluate.setText("用户评价（" + detailBean.getComNum() + "）");
        if (detailBean.getComNum() == 0) {
            comEmpty = true;
            mTvReviews.setText("该商品暂无评价");
            mTvReviews.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        } else {
            comEmpty = false;
            mTvReviews.setText("查看" + detailBean.getComNum() + "条评价");
        }
        final List<ShopDetailBean.ComListBean> comList = detailBean.getComList();
        if (comList != null && comList.size() > 0) {
            mEvaluateAdapter.setNewData(comList);
        } else {
            mRvFoodEvaluate.setVisibility(View.GONE);
        }
        final ShopDetailBean.ShopMapBean map = detailBean.getMap();
        if (map != null) {
            bean = map;
            mGoodsImgListBeans.clear();
            final String starttime = bean.getStarttime();
            if (TextUtils.isEmpty(starttime)) {
                mTvStartTime.setVisibility(View.GONE);
            } else {
                mTvStartTime.setVisibility(View.VISIBLE);
                Date date = null;
                try {
                    date = CalendarUtils.string2Date(starttime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (curTime >= date.getTime()) {
                    mTvStartTime.setVisibility(View.GONE);
                } else {
                    mTvStartTime.setText(CalendarUtils.date2String(date) + "开售后发货");
                }
            }
            if (!TextUtils.isEmpty(bean.getActivityName())) {
                mTvStartTime.setVisibility(View.VISIBLE);
                mTvStartTime.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
                mTvStartTime.setText(bean.getActivityName());
            }
            if (!TextUtils.isEmpty(bean.getVido())) {
                mGoodsImgListBeans.add(new GoodsImgBean(bean.getVido(), 1));
            }
            if (!TextUtils.isEmpty(bean.getImg_zt())) {
                final String[] imgZtArr = bean.getImg_zt().trim().split(",");
                for (String imgPath : imgZtArr) {
                    mGoodsImgListBeans.add(new GoodsImgBean(imgPath, 0));
                }
            }
            if (mGoodsImgListBeans.size() > 0) {
                mTvRollpagerHint.setText("1/" + mGoodsImgListBeans.size());
            }
            mBannerAdapter.notifyDataSetChanged();
//            mRollPagerView.pause();
            if (!TextUtils.isEmpty(bean.getImg_xq())) {
                final String[] imgXqArr = bean.getImg_xq().trim().split(",");
                final List<String> imgList = Arrays.asList(imgXqArr);
                mDetailAdapter.setNewData(imgList);
            }
            mTvShopDetail.setText(bean.getTradename());
            mTvShopDesc.setText(bean.getDescribed());

            String price = getPrice();

            mTvPrice.setText(price);

            if (Double.parseDouble(bean.getShopbv()) == 0.00) {
                mTvGoodsUnitBv.setText("");
            } else {
                mTvGoodsUnitBv.setText("(" + bean.getShopbv() + "BV)");
            }
            mTvUnitPrice.setText(bean.getWeight() + "g");

            final List<ShopDetailBean.ParameterBean> parameterBeans = detailBean.getcList();
            if (parameterBeans == null || parameterBeans.size() == 0) {
                mTvDetailParameter.setVisibility(View.GONE);
                mLlDetailParameter.setVisibility(View.GONE);
            } else {
                for (ShopDetailBean.ParameterBean parameterBean : parameterBeans) {
                    final View submitOrderView = View.inflate(this, R.layout.item_goods_parameter, null);
                    processParameterView(submitOrderView, parameterBean);
                }
            }
        }
        if (isFirstLoad) {
            if (showSpec == 1) {
                mOpType = 2;
                mPresenter.obtainSpecList(this, goodsId);
            }
        }
        isFirstLoad = false;
    }

    private void processParameterView(View submitOrderView, ShopDetailBean.ParameterBean parameterBean) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mLlDetailParameter.addView(submitOrderView, params);
        TextView tvCvName = submitOrderView.findViewById(R.id.tv_cv_name);
        tvCvName.setText(parameterBean.getCname());
        TextView tvCvValue = submitOrderView.findViewById(R.id.tv_cv_value);
        tvCvValue.setText(parameterBean.getCvalue());
    }

    @NotNull
    private String getPrice() {
        String price = "";
        if (!TextUtils.isEmpty(bean.getPrice()) && Double.parseDouble(bean.getPrice()) != 0.00) {
            price += "¥";
            price += bean.getPrice();
        }
        if (!TextUtils.isEmpty(bean.getMarket_price()) && Double.parseDouble(bean.getMarket_price()) != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += bean.getMarket_price();
                price += "积分";
            } else {
                price += bean.getMarket_price();
                price += "积分";
            }
        }
        if (TextUtils.isEmpty(price)) {
            price = "¥0.00";
        }
        if (tag == Constants.OB_TYPE) {
            return price.replace("¥", "") + "欧花";
        }

        return price;
    }

    @Override
    public void obtainSpecListSuccess(ShopSpecListBean listBean) {
        mSpecListBeans = listBean;
        GoodsImgBean goodsImgBean = mGoodsImgListBeans.get(0);
        if (goodsImgBean.getType() == 1) {
            goodsImgBean = mGoodsImgListBeans.get(1);

        }
        final String mainImg = goodsImgBean.getImgPath();
        mSpecListBeans.setGoodsImg(mainImg);
        showSpecPopWindow();
    }

    @OnClick({R.id.rl_joinCar, R.id.buyNowTv, R.id.rl_choose_rules, R.id.rl_user_comment
            , R.id.rl_shop_car})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_joinCar:
                mOpType = 0;
                showSpecView();
                break;
            case R.id.buyNowTv:
                mOpType = 1;
                showSpecView();
                break;
            case R.id.rl_choose_rules:
                mOpType = 2;
                showSpecView();
                break;
            case R.id.rl_user_comment:
                if (!comEmpty) {
                    Intent intent = new Intent(this, CommentActivity.class);
                    intent.putExtra(CommentActivity.TYPE_CID, goodsId);
                    startActivity(intent);
                }
                break;
            case R.id.rl_shop_car:
                CarActivity.go(this);
                break;
        }
    }

    private void submitOpt(int type) {
        if (type == 0) {
            onJoinCar(mGgId);
        } else {
            onBuy(mGgId);
        }
    }

    /**
     * 显示规格判断
     */
    public void showSpecView() {
        if (mSpecPopupWindow != null) {
            showSpecPopWindow();
        } else {
            mPresenter.obtainSpecList(this, goodsId);
        }
    }

    public void showSpecPopWindow() {
        if (mSpecPopupWindow != null && mSpecPopupWindow.isVisible()) {
            mSpecPopupWindow.dismiss();
        }
        mSpecPopupWindow = new GoodsSpecDialog(this, mSpecListBeans, mOpType, mPosition, buyNumber, tag,new GoodsSpecDialog.OnClickListener() {
            @Override
            public void onSubmit(int ggId, String name, int type, int position) {
                mPosition = position;
                mGgId = ggId;
                mTvChooseRules.setText("已选择");
                mTvSelectRules.setVisibility(View.VISIBLE);
                mTvSelectRules.setText(name);
                if (type != 2) {
                    submitOpt(type);
                }
            }

            @Override
            public void updateNumber(int number) {
                buyNumber = number;
            }

        });
//            mSpecPopupWindow.showAtLocation(this.getWindow().getDecorView(), Gravity.BOTTOM, 0, Utils.getNavigationBarHeight(this));
//        mSpecPopupWindow.showAtLocation(this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        mSpecPopupWindow.show(getSupportFragmentManager(), "goods");
    }

    /**
     * 加入购物车
     *
     * @param ggId
     */
    public void onJoinCar(int ggId) {
        mPresenter.onJoinCar(ShopDetailActivity.this, goodsId, ggId + "", buyNumber + "");
    }

    private void onBuy(int ggId) {
        mPresenter.onBuy(ShopDetailActivity.this, goodsId, "0", ggId + "", String.valueOf(buyNumber));
    }

    @Override
    public void updateShopSpecSuccess(Object o) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBean event) {
        //刷新购物车
        if (event.getCode() == Constants.EventCode.REFRESH_CAR) {
            mPresenter.obtainShopDetailInfo(this, goodsId);
        }
    }

    /**
     * 立即购买
     *
     * @param
     */
    @Override
    public void onBuySuccess(Object o) {
        if (mSpecPopupWindow != null && mSpecPopupWindow.isVisible()) {
            mSpecPopupWindow.dismiss();
        }
        JSONObject json = (JSONObject) o;
        FirmOrderBean firmOrderBean = new Gson().fromJson(json.toString(), FirmOrderBean.class);
        firmOrderBean.getProductMap().setNum(buyNumber);
        firmOrderBean.getProductMap().setProduct_id(firmOrderBean.getProductMap().getId());
        firmOrderBean.getProductMap().setAttribute_id(firmOrderBean.getGmap().getId());
        firmOrderBean.getProductMap().setgName(firmOrderBean.getGmap().getName());
        firmOrderBean.getProductMap().setPrice(firmOrderBean.getGmap().getPrice());
        firmOrderBean.getProductMap().setMarketPrice(firmOrderBean.getGmap().getMarket_price());
        firmOrderBean.getProductMap().setFreWeight(firmOrderBean.getGmap().getWeight());
        firmOrderBean.getProductMap().setFreightList(firmOrderBean.getFreightList());
        firmOrderBean.getProductMap().setTag(tag);
        firmOrderBean.getCarList().add(firmOrderBean.getProductMap());
        FirmOrderActivity1.start(this,
                firmOrderBean,
                "",
                goodsId,tag);
    }

    public void onJoinCarSuccess(Object o) {
        if (mSpecPopupWindow != null && mSpecPopupWindow.isVisible()) {
            mSpecPopupWindow.dismiss();
        }
        mPresenter.obtainShopDetailInfo(this, goodsId);
        ToastUtils.showToast(R.string.str_join_car_success);
        EventBus.getDefault().post(new EventBean(Constants.EventCode.REFRESH_CAR, null));
    }

    @Override
    public void onGoodsFollowSuccess(Object o) {
        if (isCon == 0) {
            ToastUtils.showToast("收藏成功");
            isCon = 1;
        } else {
            ToastUtils.showToast("取消收藏成功");
            isCon = 0;
        }
        mPresenter.obtainShopDetailInfo(this, goodsId);
    }

    @Override
    public void onGoodsCancleFollowSuccess(Object o) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
